<?php

namespace Georgie\PhpRbac\model;

use think\facade\Db;

class PermissionCategory extends Base
{
    protected $tableName = "permission_category";


    /**
     * 创建权限分组
     * @param $data array 创建的数据
     * @return bool
     * @author Georgie 227040015@qq.com
     */
    public function create($data = [])
    {
        if (!empty($data)) {
            $this->data($data);
        }

        $validate = new \Georgie\PhpRbac\validate\PermissionCategory();
        $validate->check($this->data_);

        if ($this->db()->where('name', $this->data_['name'])->count() > 0)
            throw new \Exception('该组名已存在');

        $this->data_['create_time'] = time();
        $this->db()->insert($this->data_);

        return true;
    }

    /**
     * 修改权限分组
     * @param $data array 修改的数据
     * @return bool
     * @author Georgie 227040015@qq.com
     */
    public function edit($data = [])
    {
        if (!empty($data)) {
            $this->data($data);
        }

        $validate = new \Georgie\PhpRbac\validate\PermissionCategory();
        $validate->check($this->data_);

        if (!$this->data_['id'])
            throw new \Exception('请传入ID');

        //检查重复，排除ID
        if ($this->db()->where('name', $this->data_['name'])->where('id', '<>', $this->data_['id'])->count() > 0)
            throw new \Exception('该组名已存在');


        $this->db()->where('id', $this->data_['id'])->update($this->data_);

        return true;
    }

    /**
     * 删除权限分组
     * @param $id integer 删除的ID
     * @return bool
     * @author Georgie 227040015@qq.com
     */
    public function del($id = 0)
    {
        $this->data(['id' => $id ?? ($this->data_['id'] ?? 0)]);
        if (!$this->data_['id']) throw new \Exception('请传入ID');

        if ((new Permission())->db()->where('category_id', $this->data_['id'])->count() > 0)
            throw new \Exception('该分组存在权限数据，请删除相关数据后重试');

        $this->db()->where('id', $this->data_['id'])->delete();

        return true;
    }

    /**
     * 根据条件获取数据
     * @param $condition array 筛选条件
     * @return array
     * @author Georgie 227040015@qq.com
     */
    public function get(array $condition = ['status' => 1])
    {
        $orm = $this->db()->where($condition);

        if (isset($condition['id']))
            return $orm->find();
        else
            return $orm->select();
    }

}